package com.route.core;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dalvik.system.DexFile;

/**
 * Created by Administrator on 2019/8/3.
 */

public class Route {

    private String TAG = "Route";

    private Context context;

    private Map<String, Class<? extends Activity>> activityMap;

    private static Route route = new Route();

    private Route() {
        activityMap = new HashMap<>();
    }

    public static Route getInstance() {
        return route;
    }

    public void putActivity(String path, Class<? extends Activity> cls) {
        if (!TextUtils.isEmpty(path) || cls != null) {
            activityMap.put(path, cls);
        }
    }

    public void init(Application application) {
        this.context = application;
        List<String> pathList = getClassNameList("com.rout.util");
        if (pathList.size() > 0) {
            for (String item : pathList) {
                try {
                    Class cls = Class.forName(item);
                    //判断是否为IRoute的实现类
                    if (IRoute.class.isAssignableFrom(cls)) {
                        Object object = cls.newInstance();
                        if (object instanceof IRoute) {
                            IRoute iRoute = (IRoute) object;
                            iRoute.putActivity();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private List<String> getClassNameList(String packageName) {
        List<String> list = new ArrayList<>();
        String path = null;
        try {
            path = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
            DexFile dexFile = new DexFile(path);
            Enumeration<String> enumeration = dexFile.entries();
            while (enumeration.hasMoreElements()) {
                String name = enumeration.nextElement();
                if (name.contains(packageName)) {
                    list.add(name);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public void jumpActivity(String path, Bundle bundle) {
        Class<? extends Activity> cls = activityMap.get(path);
        if (cls == null) {
            return;
        }
        Intent intent = new Intent().setClass(context, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        context.startActivity(intent);
    }
}